import 'dart:async';
import 'dart:io';
import 'dart:isolate';

import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:flutter_tts/flutter_tts.dart';

late FlutterTts flutterTts;

Future<void> ttsInit() async {
  flutterTts = FlutterTts();

  if (!Platform.isAndroid) {
    return;
  }

  await flutterTts.setLanguage('zh-CN');
  await flutterTts.setVolume(1.0);
  await flutterTts.setPitch(1.0);
  await flutterTts.setSpeechRate(1.0);
}

Future<void> speakText(String text1) async {
  if (!Platform.isAndroid) {
    return;
  }

  await flutterTts.speak(text1);
}

bool speaking = false;
int ttsStart = 0;
bool ttsPause = false;
double speed = 1.0;

void setPause() {
  ttsPause = true;
  flutterTts.pause();
}

bool sendable = true;
Future<void> sendPos(SendPort? sendPort, int i) async {
  if (sendable) {
    sendable = false;
    try {
      sendPort?.send(i);
      sendable = true;
    } finally {
      // ignore: control_flow_in_finally
      return;
    }
  }
}

late Timer repeator;

Future<void> speakList(List<String> list1, SendPort? sendPort) async {
  await flutterTts.awaitSpeakCompletion(true);
  speaking = true;
  flutterTts.setSpeechRate(speed);
  //print('fhz: text block num: ${list1.length}');
  for (int i = ttsStart; i < list1.length; i++) {
    //bool fg = await FlutterForegroundTask.isAppOnForeground;
    FlutterForegroundTask.updateService(notificationText: 'Play $i');
    sendPos(sendPort, i);
    //if (fg) sendPos(sendPort, i);
    await speakText(list1[i]);
    await flutterTts.awaitSpeakCompletion(true);
    if (ttsPause) {
      ttsStart = i;
      break;
    }
  }
  FlutterForegroundTask.stopService();
  speaking = false;
}
